package net.net23.sysdent.ui;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import net.net23.sysdent.sql.DBSet;

import com.csvreader.CsvWriter;

public class JResult extends JTable {

	private static final long serialVersionUID = 8638954572625688914L;

	private TableModel model;

	public JResult() {
	}

	public void updateModel(DBSet set) throws Exception {
		if (set != null) {
			try {
				ResultSetMetaData metadata = set.getMetadata();
				Vector<String> columnNames = new Vector<String>();
				int columnCount = metadata.getColumnCount();
				for (int i = 1; i <= columnCount; i++) {
					columnNames.add(metadata.getColumnName(i));
				}
				Vector<Vector<Object>> data = new Vector<Vector<Object>>();
				while (set.next()) {
					Vector<Object> row = new Vector<Object>();
					for (int i = 1; i <= columnCount; i++) {
						Object obj =set.getObject(i);
//						if( obj == null ){
//							System.out.println( "["+metadata.getColumnName(i)+":NULL]" );
//						}else{
//							System.out.println( "["+metadata.getColumnName(i)+":"+obj.getClass()+"]" );	
//						}
						if (obj instanceof Clob){
							Clob clob = (Clob) obj;
								obj = getReaderContent(clob.getCharacterStream());
						}
						row.add(obj);
					}
					data.add(row);
				}
				model = new DefaultTableModel(data, columnNames);
				setModel(model);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void saveResult(File file, String separator) throws IOException {
		//mandar a archivo
		
		int cols = getModel().getColumnCount();
		int rows = getModel().getRowCount();
		CsvWriter pw = new CsvWriter(file.getAbsolutePath());
		if (separator!=null && separator.length()>0){
		pw.setDelimiter(separator.charAt(0));
		}
		for (int i=0 ; i< cols; i++){
			pw.write(getModel().getColumnName(i));
		}
		pw.endRecord();
		
		for (int i = 0; i < rows; i++) {
			
			for (int j = 0; j < cols; j++) {
				pw.write(String.valueOf(getModel().getValueAt(i, j)));
			}
			pw.endRecord();
		}
		
		pw.close();
	}
	
//	public static void freeClob(final Clob b) {
//		if (b == null) {
//			return;
//		}
//		try {
//			b.
//				CLOB _b = (CLOB) b;
//				if (_b.isTemporary()) {
//					CLOB.freeTemporary(_b);
//			}
//		} catch (Exception e) {
//			// e.printStackTrace();
//		}
//	}
	
	public static String getReaderContent(final Reader content) throws Exception {
		try {
			char[] bs = new char[1024];
			StringBuffer buffer = new StringBuffer();
			while (true) {
				int i = content.read(bs);
				if (i == -1) {
					break;
				}
				buffer.append(new String(bs, 0, i));
			}
			return buffer.toString();
		} finally {
			if (content!=null){
			content.close();
		}
	}
	}

}
